<?php

namespace app\admin\controller\dts\approve;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
/**
 * 采购清单管理
 *
 * @icon fa fa-circle-o
 */
class Procure extends Backend
{

    /**
     * Let模型对象
     * @var \app\admin\model\dts\approve\procure
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dts\approve\Procure;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    protected $defaultJoin = [
        ['admin admin', 'admin.id = procure.admin_id', 'left'],
        ['dts_dept dept', 'dept.id = procure.dept_id', 'left'],
        ['dts_classes classes', 'classes.id = procure.classes_id', 'left'],
        ['dts_config_capital config', 'config.id = procure.config_capital_id', 'left'],
        ['admin examine', 'examine.id = procure.examine_dept_id', 'left'],
        ['admin leader', 'leader.id = procure.examine_leader_id', 'left'],
        ['admin fenguan', 'fenguan.id = procure.examine_fenguan_id', 'left'],
        ['admin yuanchang', 'yuanchang.id = procure.examine_yuanchang_id', 'left'],
        ['admin copy', 'FIND_IN_SET(copy.id,procure.copy_ids)', 'left'],
    ];

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = Db::name('dts_approve_procure')->alias('procure')
            ->field('procure.*,admin.nickname as admin__nickname,dept.name as dept__name,classes.name as classes__name,config.name as config__name,
            examine.nickname as examine__nickname,leader.nickname as leader__nickname,fenguan.nickname as fenguan__nickname,yuanchang.nickname as yuanchang__nickname,
            ifnull(GROUP_CONCAT(DISTINCT copy.nickname),"") copy__nickname')
            ->join($this->defaultJoin)
            ->where($where)
            ->order($sort, $order)
            ->group('procure.id')
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => paginateList($list));

            return json($result);
        }

        return $this->view->fetch();
    }

    public function export($ids = null) {

        $row = Db::name('dts_approve_procure')->alias('procure')
        ->field('procure.*,admin.nickname as admin__nickname,dept.name as dept__name,classes.name as classes__name,config.name as config__name,examine.nickname as examine__nickname,leader.nickname as leader__nickname')
        ->join([
            ['admin admin', 'admin.id = procure.admin_id', 'left'],
            ['dts_dept dept', 'dept.id = procure.dept_id', 'left'],
            ['dts_classes classes', 'classes.id = procure.classes_id', 'left'],
            ['dts_config_capital config', 'config.id = procure.config_capital_id', 'left'],
            ['admin examine', 'examine.id = procure.examine_dept_id', 'left'],
            ['admin leader', 'leader.id = procure.examine_leader_id', 'left'],
            ['admin fenguan', 'fenguan.id = procure.examine_fenguan_id', 'left'],
            ['admin yuanchang', 'yuanchang.id = procure.examine_yuanchang_id', 'left'],
        ])
        ->where('procure.id', $ids)
        ->find();

        if(!$row) {
            $this->error('未查询到导出记录');
        }

        $row = paginateItem($row);

        $list = Db::name('dts_approve_examine_log')->alias('log')
        ->field('log.*,examine.nickname as examinename')
        ->join([
            ['admin examine', 'examine.id = log.examine_id', 'left']
        ])
        ->where(['category' => 'procure', 'approve_id' => $row['id']])
        ->order('id', 'asc')
        ->select();

        try {
            //读取模板
            $reader = IOFactory::createReader('Xlsx');
            $spreadsheet = $reader->load('template/procure.xlsx');
            //指向激活的工作表
            $worksheet = $spreadsheet->getActiveSheet();     
            $worksheet->setTitle('事前审批');
            $wizard = new \PhpOffice\PhpSpreadsheet\Helper\Html;

            //向模板表中写入数据
            $worksheet->setCellValue('C3', $row['dept']['name'] ? $row['dept']['name'] : $row['classes']['name']);
            $worksheet->setCellValue('F3', $row['admin']['nickname']);
            $worksheet->setCellValue('I3', date('Y-m-d', strtotime($row['fortime'])));

            $worksheet->getStyle('C5')->getAlignment()->setWrapText(true);
            $charset = mb_detect_encoding($row['forcause']);
            $forcause = preg_replace('/(.{80})/', "$1\n", $row['forcause']);
            $worksheet->setCellValue('C5', str_replace('?', '', mb_convert_encoding($forcause, 'UTF-8', $charset)));

            $worksheet->setCellValue('C10', $row['config']['name']);
            $worksheet->setCellValue('D12', $row['budget_amount_float']);
            $worksheet->setCellValue('H12', $row['budget_amount_string']);

            $key = 14;
            foreach($list as $item) {
                if($key > 26) {
                    break;
                }
                $arr = explode('-', $item['examine_result']);
                $examine_result = sizeof($arr) >= 2 ? $arr[1] : $arr[0];
                $worksheet->setCellValue('C'.$key, $examine_result);
                $worksheet->setCellValue('I'.$key, $item['examinename']);
                $Ikey = $key + 2;
                $worksheet->setCellValue('I'.$Ikey, date('Y-m-d H:i', $item['createtime']));
                $key = $key + 4;
            }

            //输出到浏览器
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="'.mb_convert_encoding(substr($row['forcause'], 0, 50), 'UTF-8', $charset).'.xlsx"');
            header('Cache-Control: max-age=0');
            
            ob_clean();
            ob_start();
            //按照指定格式生成Excel文件
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');

            /* 释放内存输出 */
            ob_end_flush();

        }catch(Exception $e) {
            Log::write($e->getMessage());
        }


    }
}
